package com.crm.system.service.impl.cluePoolManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.dao.mapper.cluePoolManager.CluePoolCompanyMapper;
import com.crm.model.entity.cluePoolManager.CluePoolCompany;
import com.crm.model.entity.cluePoolManager.CluePoolCompanyExample;
import com.crm.model.entity.cluePoolManager.CluePoolManager;
import com.crm.model.entity.cluePoolManager.CluePoolPublic;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.cluePoolManager.CluePoolOpenSeaQO;
import com.crm.model.vo.cluePoolManager.CluePoolCompanyVO;
import com.crm.model.vo.cluePoolManager.CluePoolPubliclOpenSeaVO;
import com.crm.service.cluePoolManager.CluePoolCompanyDbService;
import com.crm.service.cluePoolManager.CluePoolPublicDbService;
import com.crm.system.service.cluePoolManager.CluePoolCompanyService;
import com.crm.system.service.permissionManagement.SysCompanyService;
import com.crm.system.service.user.UserAccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author luojie
 * @date 2020/12/25 14:57
 */
@Service
public class CluePoolCompanyServiceImpl implements CluePoolCompanyService {

    @Autowired
    private CluePoolCompanyDbService cluePoolCompanyDbService;

    @Autowired
    private CluePoolPublicDbService cluePoolPublicDbService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private UserAccountService userAccountService;

    @Override
    public Boolean addPoolCompany(List<String> companyIdList,String cluePoolId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        companyIdList.stream().forEach(companyId ->{
            CluePoolCompany cluePoolCompany = new CluePoolCompany();
            cluePoolCompany.setCluePollCompanyId(CommonUtils.getGUID());
            cluePoolCompany.setCluePollId(cluePoolId);
            cluePoolCompany.setCompanyId(companyId);
            cluePoolCompany.setCreateTm(new Date());
            //添加方式：1-分公司公有池；2-使用组设置
            cluePoolCompany.setAddMethod(1);
            cluePoolCompany.setCreatePeopleId(userAccount.getAccountId());
            //权限类型：1-公司；2-个人
            cluePoolCompany.setPermissionType("1");
            cluePoolCompany.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            cluePoolCompanyDbService.insertCluePoolCompany(cluePoolCompany);
        });
        return true;
    }


    /**
     * @author wll
     * info 用户模块-线索池管理-线索池公海表单(公司 我参与的)
     * @return
     */
    @Override
    public DhPageInfo<CluePoolPubliclOpenSeaVO> getCluePoolCompanyInfo(CluePoolOpenSeaQO cluePoolOpenSeaQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder,List<CluePoolCompany> cluePoolCompanies,UserAccount userAccount) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //入口没控制 可能存在多条记录
        HashSet<String> set = new HashSet<String>();//去重线索池id
        List list = new ArrayList();
        if(null !=cluePoolCompanies && cluePoolCompanies.size()>0){
            if(cluePoolOpenSeaQO.getTabType() == 2){//公司公海
                for (CluePoolCompany cluePoolCompany:cluePoolCompanies) {
                    //公司id匹配上    查询权限类型为公司的数据
                    if(cluePoolCompany.getPermissionType().equals("1")){
                        set.add(cluePoolCompany.getCluePollId());
                    }
                }
            }else{//我参与的公海
                for (CluePoolCompany cluePoolCompany:cluePoolCompanies) {
                    //公司id匹配上    查询权限类型为个人的数据 同时使用人员id匹配上
                    if(cluePoolCompany.getPermissionType().equals("2")){
                        if(StringUtils.isNotBlank(cluePoolCompany.getUsePeopleId()) && cluePoolCompany.getUsePeopleId().equals(userAccount.getAccountId())){
                            set.add(cluePoolCompany.getCluePollId());
                        }
                    }
                }
            }
        }

            Iterator<String> iterator = set.iterator();
            while(iterator.hasNext()){
                list.add(iterator.next());
            }

            //查询公共池数据
            Integer dateUnit = 0;
            if (StringUtils.isNotEmpty(cluePoolOpenSeaQO.getDateType())) {
                if ("thisWeek".equals(cluePoolOpenSeaQO.getDateType())) {
                    //本周
                    dateUnit = 1;
                }
                if ("thisMonth".equals(cluePoolOpenSeaQO.getDateType())) {
                    //本月
                    dateUnit = 2;
                }
                if ("thisYear".equals(cluePoolOpenSeaQO.getDateType())) {
                    //本年
                    dateUnit = 3;
                }
            }

            //拼凑表格排序内容
            String order = "p.default_mark desc"; //是否是默认池子：0-不是默认；1-默认池子
            if(StringUtils.isNotEmpty(sortName) && StringUtils.isNotEmpty(sortOrder)){
                switch(sortName){
                    case "createTm":
                    {
                        order= order + ",p.create_tm " + sortOrder;
                    }
                    break;
                    case "poolType":
                    {
                        order= order + ",p.pool_type " + sortOrder;
                    }
                    break;
                    default:
                        break;
                }

            }
        Map map = new HashMap();
        map.put("list",list);
        map.put("cluePoolOpenSeaQO",cluePoolOpenSeaQO);
        map.put("dateUnit",dateUnit);
        map.put("order",order);
        List<CluePoolPubliclOpenSeaVO> cluePoolPubliclOpenSeaVOList = cluePoolPublicDbService.selectCluePoolPublicInfo(map);
        PageInfo<CluePoolPubliclOpenSeaVO> pageInfo = new PageInfo<CluePoolPubliclOpenSeaVO>(cluePoolPubliclOpenSeaVOList);
        return new DhPageInfo<CluePoolPubliclOpenSeaVO>(pageInfo, cluePoolPubliclOpenSeaVOList);
    }

    /**
     * 私有池查询使用组人员
     * @param cluePollId   ---线索池主键
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPersonByDistributePermission(String cluePollId) {
        return cluePoolCompanyDbService.selectPersonByDistributePermission(cluePollId,(short) StatusCodeEnum.NORMAL_CODE.getState());
    }

    /**
     * 私有池查询使用组公司
     * @param cluePollId   ---线索池主键
     * @return
     */
    @Override
    public List<Map<String, Object>> selectCompanyByDistributePermission(String cluePollId) {
        return cluePoolCompanyDbService.selectCompanyByDistributePermission(cluePollId,(short) StatusCodeEnum.NORMAL_CODE.getState());
    }

    @Override
    public List<JSONObject> selectPoolPersonalPermission(String cluePollId) {
        List<JSONObject> companyListVO = new ArrayList<>();
        //查询所有公司
        List<SysCompany> sysCompanies = sysCompanyService.selectSysCompanyList();
        sysCompanies.stream().forEach(company -> {
            String companyId = company.getCompanyId();
            String companyName = company.getCompanyName();
            JSONObject companyVO = new JSONObject();
            companyVO.put("companyId",companyId);
            companyVO.put("companyName",companyName);
            List<UserAccount> userAccountList = userAccountService.selectUserAccountByCompanyId(companyId);
            List<JSONObject> accountListVO = new ArrayList<>();
            userAccountList.stream().forEach(userAccount -> {
                String permissionType = "2"; //个人
                //根据公司id和个人id查询是否有权限
                CluePoolCompany cluePoolCompany = cluePoolCompanyDbService.selectByCluePoolIdAndCompanyIdAndUserPeopleId(cluePollId,companyId,userAccount.getAccountId(),permissionType);
                JSONObject accountVO = new JSONObject();
                if(cluePoolCompany!=null){
                    accountVO.put("accountId",userAccount.getAccountId());
                    accountVO.put("userName",userAccount.getUserName());
                    accountVO.put("selected",true);
                }else {
                    accountVO.put("accountId",userAccount.getAccountId());
                    accountVO.put("userName",userAccount.getUserName());
                    accountVO.put("selected",false);
                }
                accountListVO.add(accountVO);
            });

            companyVO.put("account",accountListVO);
            companyListVO.add(companyVO);
        });
        return companyListVO;
    }

    @Override
    public List<JSONObject> selectPoolCompanyPermission(String cluePollId) {
        List<JSONObject> companyVOs = new ArrayList<>();
        List<SysCompany> sysCompanyList = sysCompanyService.selectSysCompanyList();
        //权限类型：1-公司；2-个人
        String permissionType = "1";
        List<CluePoolCompany> cluePoolCompanyList = cluePoolCompanyDbService.selectByCluePoolIdAndPermissionType(cluePollId,permissionType);
        sysCompanyList.stream().forEach(company -> {
            JSONObject companyVO = new JSONObject();
            companyVO.put("companyId",company.getCompanyId());
            companyVO.put("companyName",company.getCompanyName());
            //判断管理用户id集合里面如果包含账号id设置为true
            Boolean result = false;
            for (CluePoolCompany cluePoolCompany : cluePoolCompanyList) {
                if(cluePoolCompany.getCompanyId().equals(company.getCompanyId())){
                    result = true;
                }

            }
            companyVO.put("selected",result);
            companyVOs.add(companyVO);
        });
        return companyVOs;
    }

    @Override
    public Boolean addUsePeople(String cluePoolId, List<JSONObject> usePeopleList) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        usePeopleList.stream().forEach(company ->{
            JSONArray accountList = company.getJSONArray("account");

            for(int i=0;i<accountList.size();i++) {
                if(accountList.getJSONObject(i).getBoolean("selected")){
                    CluePoolCompany cluePoolCompany = new CluePoolCompany();
                    cluePoolCompany.setCluePollCompanyId(CommonUtils.getGUID());
                    cluePoolCompany.setCluePollId(cluePoolId);
                    cluePoolCompany.setCompanyId(company.getString("companyId"));
                    cluePoolCompany.setAddMethod(2);
                    cluePoolCompany.setUsePeopleId(accountList.getJSONObject(i).getString("accountId"));
                    cluePoolCompany.setPermissionType("2");
                    cluePoolCompany.setCreatePeopleId(userAccount.getAccountId());
                    cluePoolCompany.setCreateTm(new Date());
                    cluePoolCompany.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                    cluePoolCompanyDbService.insertCluePoolCompany(cluePoolCompany);
                }
            }
        });
        return true;
    }

    @Override
    public Boolean addUserCompany(String cluePoolId, List<String> companyIdList) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        companyIdList.stream().forEach(companyId ->{
            CluePoolCompany cluePoolCompany = new CluePoolCompany();
            cluePoolCompany.setCluePollCompanyId(CommonUtils.getGUID());
            cluePoolCompany.setCluePollId(cluePoolId);
            cluePoolCompany.setCompanyId(companyId);
            cluePoolCompany.setAddMethod(2);
            cluePoolCompany.setPermissionType("1");
            cluePoolCompany.setCreatePeopleId(userAccount.getAccountId());
            cluePoolCompany.setCreateTm(new Date());
            cluePoolCompany.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            cluePoolCompanyDbService.insertCluePoolCompany(cluePoolCompany);
        });
        return true;
    }

    @Override
    public Boolean addCreatePeopleCompany(String cluePoolId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CluePoolCompany cluePoolCompany = new CluePoolCompany();
        cluePoolCompany.setCluePollCompanyId(CommonUtils.getGUID());
        cluePoolCompany.setCluePollId(cluePoolId);
        cluePoolCompany.setCompanyId(userAccount.getCompanyId());
        cluePoolCompany.setAddMethod(2);
        cluePoolCompany.setUsePeopleId(userAccount.getAccountId());
        cluePoolCompany.setPermissionType("2");
        cluePoolCompany.setCreatePeopleId(userAccount.getAccountId());
        cluePoolCompany.setCreateTm(new Date());
        cluePoolCompany.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        Boolean result = cluePoolCompanyDbService.insertCluePoolCompany(cluePoolCompany);
        return result;
    }

    @Override
    public List<CluePoolCompany> selectCompanyByPoolId(String cluePoolId) {
        List<CluePoolCompany> cluePoolCompanyList = cluePoolCompanyDbService.selectByCluePoolIdAndPermissionType(cluePoolId,"1");
        return cluePoolCompanyList;
    }

    @Override
    public List<CluePoolCompany> selectByExample(CluePoolCompanyExample cluePoolCompanyExample) {
        return cluePoolCompanyDbService.selectByExample(cluePoolCompanyExample);
    }

    @Override
    public Boolean deleteUsePeople(String cluePoolId, String permissionType) {
        Boolean result = cluePoolCompanyDbService.updatePoolCompany(cluePoolId,permissionType);
        return result;
    }

}
